//
//  QDStationDetailViewController.swift
//  
//
//  Created by YueWen on 2019/3/3.
//

import UIKit
import HandyJSON

/// 站点详细内容
final class QDStationDetailViewCell: NWTableViewCell {
    
    /// 显示icon
    let iconImageView = UIImageView()
    /// 显示大标题
    let titleLabel = UILabel()
    /// 显示详细内容
    let subtitleLabel = UILabel()
    
    override func buildView() {
        super.buildView()
        
        bottomLineView.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.9411764706, blue: 0.9333333333, alpha: 1)
        bottomLineInset.left = 20
        bottomLineInset.right = 20
        
        iconImageView.clipsToBounds = true
        iconImageView.backgroundColor = .white
        
        titleLabel.font = Font.regular.font(size: 14)
        titleLabel.textColor = QDColors.black
        titleLabel.text = "无障碍电梯（地面—站厅）"
        
        subtitleLabel.font = Font.regular.font(size: 13)
        subtitleLabel.textColor = QDColors.gray2
        subtitleLabel.numberOfLines = 0
        subtitleLabel.text = "凤凰山路站：开发区45路，开发区806路，胶南11路，黄岛107路，黄岛212路外环，黄岛310路，黄岛3路，黄岛西10路西线，K22路，108路，215路，217路，218路，306路，806路，青西快线"
        
        contentView.addSubview(iconImageView)
        contentView.addSubview(titleLabel)
        contentView.addSubview(subtitleLabel)
        
        iconImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(20)
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(10)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(iconImageView.snp.right).offset(5)
            make.centerY.equalTo(iconImageView)
            make.height.equalTo(20)
        }
        
        subtitleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().inset(15)
            make.top.equalTo(iconImageView.snp.bottom).offset(5)
            make.bottom.equalToSuperview().inset(10)
        }
    }
}

/// 车站信息
private struct QDStationInstallation: HandyJSON {
    
    /// 分类
    enum QDStationInstallationType: String {
        /// 基础设施
        case base = "1"
        /// 出入
        case enter = "2"
        /// 服务
        case service = "3"
        /// 公交
        case bus = "4"
        /// 未知
        case unknown
    }
    
    /// 车站id
    var id = ""
    /// 主标题
    var name = ""
    /// 描述
    var description = ""
    /// 图片路径
    var imagePath = ""
    /// 表示类型
    var installationType = "1"
    /// 类型
    var type: QDStationInstallationType {
        return QDStationInstallationType(rawValue: installationType) ?? .unknown
    }
}


/// 站点详情选择相应的代理
protocol QDStationDetailViewControllerMapAction: class {
 
    /// 点击选择后的响应
    func stationDetailViewMapAction(viewController: QDStationDetailViewController,
                                    name: String,
                                    id: String,
                                    type: QDStationDetailInfoHeaderView.ClickType)
}


/// 站点详情
final class QDStationDetailViewController: NWTableViewController {

    /// 地铁站点的id
    @objc var stationId: String = "1"
    /// 地铁站点名称
    @objc var stationName: String = "青岛站"
    /// 是否是来自线网图/是否启用设置为起点、终点
    var fromMap: Bool = false
    /// 来自线网图的代理
    weak var mapDelegate: QDStationDetailViewControllerMapAction? = nil
    /// 展示地铁信息的header，包含设为起点以及终点的响应
    private let infoHeaderView = QDStationDetailInfoHeaderView()
    /// 展示地铁信息的header,包含时间点
    private let timeHeaderView = QDStationTimeInfoHeaderView()
    /// 展示地铁信息的header，包含出入口信息
    private let tagHeaderView = QDStationTagsHeaderView()
    
    // MARK: 数据源
    
    /// 线路
    var stationLines = [QDNearMetroStation](){
        willSet {
            timeHeaderView.stationLines = newValue//设置数据
        }
    }
    
    /// 所有的设施
    private var allInstallations = [QDStationInstallation]() {
        willSet {
            baseInstallations = newValue.filter { $0.type == .base }
            enterInstallations = newValue.filter { $0.type == .enter }
            serviceInstallations = newValue.filter { $0.type == .service }
            busInstallations = newValue.filter { $0.type == .bus }
            
            currentInstallations = enterInstallations//默认为出入口信息
        }
    }
    
    /// 分类数据
    private var baseInstallations = [QDStationInstallation]()
    private var enterInstallations = [QDStationInstallation]()
    private var serviceInstallations = [QDStationInstallation]()
    private var busInstallations = [QDStationInstallation]()
    
    /// 当前的站点
    private var currentInstallations = [QDStationInstallation]() {
        didSet {
            tableView.reloadData()
        }
    }
    /// 当前顺序
    private var sortInstallations: [[QDStationInstallation]] {
        get {
            return [enterInstallations,busInstallations,baseInstallations,serviceInstallations]
        }
    }
    

    convenience init(stationId: String, stationName: String, fromMap: Bool = false,delegate: QDStationDetailViewControllerMapAction? = nil){
        self.init()
        self.stationId = stationId
        self.stationName = stationName
        self.fromMap = fromMap
        self.mapDelegate = delegate
    }
    
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        headerRefreshEnable = false
        footerRefreshEnable = false
    }
    
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDStationDetailViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        /// 不按照自适应导航栏
        tableView.ritl_setContentInsetAdjustmentBehavior {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 100
        tableView.contentInset.bottom = 15
        
        //进行站点赋值
        infoHeaderView.nameButton.setTitle(stationName, for: .normal)
        
        infoHeaderView.isEdit = fromMap
        infoHeaderView.delegate = self
        infoHeaderView.buildLayouts()
        tagHeaderView.delegate = self
        
        infoHeaderView.nameButton.controlEvents(.touchDown) { [unowned self](_) in
            self.navigationController?.popViewController(animated: true)
        }
        
        view.addSubview(infoHeaderView)

        //开始请求
        requestStationDetail()
    }
    
    /// 更新顶部主视图
    private func updateHeaderView(){
        
        let headerView = UIView()
        
        let infoHeight = infoHeaderView.height
        let timeHeight = timeHeaderView.height(count: stationLines.count)
        let tagHeight = CGFloat(60)
        
        headerView.addSubview(timeHeaderView)
        headerView.addSubview(tagHeaderView)

        infoHeaderView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(infoHeight)
        }

        tableView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalToSuperview().offset(infoHeight)
        }

        timeHeaderView.ritl_originPoint = .zero
        timeHeaderView.ritl_size = CGSize(width: ritl_width, height: timeHeight)
        
        tagHeaderView.ritl_originPoint = CGPoint(x: 0, y: timeHeight)
        tagHeaderView.ritl_size = CGSize(width: ritl_width, height: tagHeight)

        headerView.ritl_height = timeHeight + tagHeight
        tableView.tableHeaderView = headerView

//
//
//        let timeHeight = timeHeaderView.height(count: stationLines.count)
//        timeHeaderView.ritl_height = timeHeight
//        tagHeaderView.ritl_originY = timeHeight
//
//        guard let headerView = tableView.tableHeaderView else {
//            return
//        }
//
//        let tagHeight = CGFloat(60)
//        headerView.ritl_height = /*infoHeight + */ timeHeight + tagHeight
//        timeHeaderView.stationLines = stationLines//设置数据
    }
    
    
    override func makeTableViewConstraints() { }
    

    // MARK: NavigationBar
    override var nav_barHidden: Bool { return true }
    override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }

}



extension QDStationDetailViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return currentInstallations.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let detailCell = cell as? QDStationDetailViewCell {
            
            let station = currentInstallations[indexPath.row]
            
            //设置值
            detailCell.titleLabel.text = station.name
            detailCell.subtitleLabel.text = station.description
            detailCell.bottomLineView.isHidden = (indexPath.row == currentInstallations.count)
            detailCell.iconImageView.sd_setImage(with: URL(string: station.imagePath), completed: nil)
        }
        
        return cell
    }
}



extension QDStationDetailViewController: QDStationDetailInfoHeaderViewDelegate {
    
    func stationDetailInfoHeaderView(view: QDStationDetailInfoHeaderView, clickType: QDStationDetailInfoHeaderView.ClickType) {
//        print("\(stationId):\(stationName)\(clickType == .start ? "进站" : "出站")")
        mapDelegate?.stationDetailViewMapAction(viewController: self, name: stationName, id: stationId, type: clickType)
    }
}



extension QDStationDetailViewController: QDStationTagsHeaderViewDelegate {
    
    func stationTagsHeaderView(view: QDStationTagsHeaderView, clickAt index: Int) {
        currentInstallations = sortInstallations[index]
    }
}


extension QDStationDetailViewController {
    
    private struct QDStationDetailContainer: HandyJSON {
        
        /// 线路信息
        var lineData = [QDNearMetroStation]()
        /// 设施信息
        var installation = [QDStationInstallation]()
    }
    
    /// 请求站点详情信息
    private func requestStationDetail(){
        
        view.showWatingHUD()
        
        QDNetworkingManager.request(url: stationDetailUrl, paramteres: ["stationId":stationId], success: { (msg, data) in
            
            self.view.dismissHUD()
            
            // 如果能生成数据
            guard let container = QDStationDetailContainer.deserialize(from: data) else {
                self.view.showTextHUD(text: "数据解析失败!"); return
            }
            
            self.stationLines = container.lineData
            self.allInstallations = container.installation
            
            //刷新header
            self.updateHeaderView()
            
        }) { (msg, errorType) in
            self.view.showTextHUD(text: msg)
        }
    }
}
